'''
Created on 30 Mar 2010

@author: as371
'''
import os,subprocess,shutil,string
folder = '/home/as371/Documents/101_ObjectCategories'
testFolder = '/home/as371/Documents/test'


def cropAndRename (folder):
    print 'start'
    for dirname, dirnames, fs in os.walk(folder):
        for subdirname in dirnames:
            for notused_dirname, notused_dirnames, filenames in os.walk(os.path.join(dirname, subdirname)):
                    arg1 = 's/image/%s/' % subdirname
                    arg2 = "%s/*" % os.path.join(dirname, subdirname)
                    result = subprocess.Popen(["rename %s %s" % (arg1,arg2) ,'rename', arg1 ,arg2 ], stdout=subprocess.PIPE, shell=True).communicate()[0]
                    #print 'rename', "'s/image/%s/'" % subdirname,"%s/*" % os.path.join(dirname, subdirname)
                    updateFilename = []
                    for filename in filenames:
                        updateFilename.append(string.replace(filename, 'image', subdirname))
                        
                    for filename in updateFilename[:11]:
                        src = os.path.join(dirname, subdirname, filename)
                        dst =os.path.join(testFolder, filename)
                        shutil.move(src, dst)
                        
                    for filename in updateFilename[50:]:
                        path = os.path.join(dirname, subdirname, filename)
                        os.remove(path)
                    
    print 'end'

cropAndRename(folder)